package com.example.listgame.fragment;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.listgame.DBOpenHelper;
import com.example.listgame.R;

import java.util.ArrayList;
import java.util.HashMap;

public class MediumFragment extends Fragment {

    private ListView mTvMedium;
    private DBOpenHelper dbOpenHelper;
    private String getName;
    private int ID,getPoint;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment,container,false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTvMedium = view.findViewById(R.id.lv);
        ArrayList<HashMap<String,Object>> listItem = new ArrayList<HashMap<String, Object>>();
        dbOpenHelper = new DBOpenHelper(getActivity(),"db_userinfo.db",null,1);
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        Cursor cursor = db.query("UserInfo",new String[]{"username","mpoint"},null,null,null,null,"mpoint desc");
        if (cursor != null && cursor.getCount() > 0){
            while (cursor.moveToNext()){
                ID = cursor.getPosition()+1;
                getName = cursor.getString(cursor.getColumnIndex("username"));
                getPoint = cursor.getInt(cursor.getColumnIndex("mpoint"));
                HashMap<String,Object> map = new HashMap<String,Object>();
                map.put("id",ID);
                map.put("username",getName);
                map.put("mpoint",getPoint);
                listItem.add(map);
                SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(),listItem,R.layout.layout_ranking_item,
                        new String[]{"id","username","mpoint"},new int[]{R.id.tv_ranking,R.id.tv_name,R.id.tv_course});
                mTvMedium.setAdapter(simpleAdapter);
            }
        }
        cursor.close();
        db.close();
    }
}
